package network.TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA
 * Description:服务端
 * User:22954
 * Date:2024-04-03
 * Time:16:53
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);//获取端口9999----尽量不适用1-1024端点----需要本机不存在服务已占用9999端点
        System.out.println("got port 9999, waiting linked");
        Socket socket = serverSocket.accept();//监听端口,程序堵塞,直至有客户端接入,返回Socket对象,程序继续
        System.out.println("got client socket : " + socket.getClass());
        InputStream inputStream = socket.getInputStream();
//        byte[] buf = new byte[1024];
//        int readLen = 0;
//        while ((readLen = inputStream.read(buf)) != -1) {
//            System.out.println(new String(buf, 0, readLen));
//        }
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String data;
        while ((data = br.readLine()) != null) {
            System.out.println(data);
        }
        OutputStream outputStream = socket.getOutputStream();
//        outputStream.write("hello client".getBytes());
//        socket.shutdownOutput();//设置写入结束标记
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream));
        bw.write("hello client");
        bw.flush();
        socket.shutdownOutput();//设置写入结束标记
//        inputStream.close();
//        outputStream.close();
        br.close();
        socket.close();
        System.out.println("broken linked");
    }
}
